// utils/websocketManager.js
class WebSocketManager {
  constructor() {
    this.ws = null;
    this.messageHandlers = new Map();
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
    this.connected = false;
  }

  connect(url, onOpen, onClose, onError) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      return Promise.resolve();
    }

    return new Promise((resolve, reject) => {
      try {
        this.ws = new WebSocket(url);

        this.ws.onopen = (event) => {
          this.connected = true;
          this.reconnectAttempts = 0;
          onOpen && onOpen(event);
          resolve();
        };

        this.ws.onmessage = (event) => {
          try {
            const message = JSON.parse(event.data);
            this.dispatchMessage(message);
          } catch (error) {
            console.error('消息解析错误:', error);
          }
        };

        this.ws.onclose = (event) => {
          this.connected = false;
          onClose && onClose(event);
          this.handleReconnect(url, onOpen, onClose, onError);
        };

        this.ws.onerror = (error) => {
          onError && onError(error);
          reject(error);
        };

      } catch (error) {
        reject(error);
      }
    });
  }

  handleReconnect(url, onOpen, onClose, onError) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);

      setTimeout(() => {
        this.connect(url, onOpen, onClose, onError).catch(console.error);
      }, this.reconnectInterval);
    }
  }

  registerHandler(messageType, handler) {
    if (!this.messageHandlers.has(messageType)) {
      this.messageHandlers.set(messageType, []);
    }
    this.messageHandlers.get(messageType).push(handler);
  }

  unregisterHandler(messageType, handler) {
    if (this.messageHandlers.has(messageType)) {
      const handlers = this.messageHandlers.get(messageType);
      const index = handlers.indexOf(handler);
      if (index > -1) {
        handlers.splice(index, 1);
      }
    }
  }

  dispatchMessage(message) {
    const handlers = this.messageHandlers.get(message.type) || [];
    handlers.forEach(handler => handler(message));
  }

  send(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(message));
      return true;
    }
    return false;
  }

  close() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    this.connected = false;
  }

  isConnected() {
    return this.connected;
  }
}

// 创建单例实例
const webSocketManager = new WebSocketManager();
export default webSocketManager;
